package com.lwc.backendsinglestructure.strategy.registerStrategy;

import com.lwc.backendsinglestructure.domain.dto.user.RegisterForm;
import com.lwc.backendsinglestructure.domain.entity.User;
import com.lwc.backendsinglestructure.exception.BusinessException;
import com.lwc.backendsinglestructure.exception.ErrorCode;
import com.lwc.backendsinglestructure.mapper.UserMapper;
import com.lwc.backendsinglestructure.utils.cache.CacheUtil;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 邮箱注册策略
 */
@Component("EMAIL_REGISTER")
public class EamilRegisterStrategy extends BaseRegisterStrategy {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CacheUtil cacheUtil;

    /**
     * 注册方法
     *
     * @param registerForm
     * @return
     */
    @Override
    protected Boolean doRegister(RegisterForm registerForm) {
        // todo 允许注册
        User newUser = new User();
        newUser.setUsername(registerForm.getUsername());
        newUser.setPassword(registerForm.getPassword());
        newUser.setNickName("用户1");
        newUser.setRole("普通用户");
        newUser.setEmail(registerForm.getEamil());
        newUser.setPhone(registerForm.getPhone());
//        newUser.setInviteCode();
        int insert = userMapper.insert(newUser);
        return insert>0;
    }

    /**
     * 具体校验逻辑
     * @param registerForm
     */
    @Override
    protected void preValidate(RegisterForm registerForm) {
        // 1.先校验验证码
        String captcha = cacheUtil.get("captcha:register:" + registerForm.getEamil());
        if(!captcha.equals(registerForm.getCode())){
            throw new BusinessException(ErrorCode.CODE_ERROR);
        }
        // 2.参数校验
        String username = registerForm.getUsername();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOneByQuery(queryWrapper);
        // 3.判断用户是否存在
        if(user != null){
            throw new BusinessException(ErrorCode.USERNAME_REPEAT_ERROR);
        }
        // 4.校验密码与确认密码是否一致
        if(!registerForm.getPassword().equals(registerForm.getRePassword())){
            throw new BusinessException(ErrorCode.PASSWORD_ERROR);
        }
        if(registerForm.getEamil() == null){
            throw new BusinessException(ErrorCode.PHONE_NOT_FOUND_ERROR);
        }
        queryWrapper = new QueryWrapper();
        queryWrapper.eq(User::getEmail, registerForm.getEamil());
        user = userMapper.selectOneByQuery(queryWrapper);
        if( user != null){
            throw new BusinessException(ErrorCode.PHONE_REPEAT_ERROR);
        }
    }
}
